package main


import (
	"flag"
	"fmt"
	_ "gitee.com/banyanhouse/distill-micro-grpc-hystrix/micro-gateway"
	"strconv"
	"strings"

	conf "gitee.com/banyanhouse/distill-infra/config"
	"log"
	"os"

	//_ "gitee.com/Hu-Lyndon/distill-resk"
	infra "gitee.com/banyanhouse/distill-infra"

	"gitee.com/banyanhouse/distill-infra/utils"
)

var (
	Version string = "0.0.1"

	//h bool
	//
	//v bool
	serverAddress string
	configFilePath string
	//modelFilePath string
	//wwwDir        string
	//swaggerDir    string
	//port          int
)

func init()  {
	flag.StringVar(&serverAddress, "server_address", "", "set server start address")
	//flag.BoolVar(&h, "h", false, "this help")
	//flag.BoolVar(&v, "v", false, "show version and exit")
	//
	//flag.IntVar(&p, "p", -1, "get the default from config.toml app.httpPort, if value is -1.")
	//flag.StringVar(&configFilePath, "c", "", "get the ./config/config.toml, if not set value.")
	// 改变默认的 Usage，flag包中的Usage 其实是一个函数类型。这里是覆盖默认函数实现，具体见后面Usage部分的分析
	flag.Usage = usage
}

func main() {


	flag.Parse()
	//if h {
	//	log.Println("h:", h)
	//	usage()
	//}
	//
	//if v {
	//	log.Println("has args v")
	//	defaultVersion()
	//}

	// 获取程序运行，所需配置文件的路径

	if configFilePath == "" {
		configFilePath = utils.GetCurrentPath("./config/") + "/config.toml"
	}

	extensionMap := make(map[string]interface{})
	extensionMap["gatewayConfig"] = configFilePath
	// 声明配置对象
	appConfig := &conf.TomlConfig{}
	// 从文件加载配置信息
	configFiles := []string{configFilePath, utils.GetCurrentPath("../config/") + "/config.toml"}
	utils.ConfigFromSlice(configFiles, appConfig)

	// 如果传入server_address，则覆盖配置文件中的内容
	if serverAddress != "" {

		serverAddressPort := strings.Split(serverAddress, ":")
		serverPort, err := strconv.Atoi(serverAddressPort[1])
		if err != nil {
			ErrHandler(err)
		}

		if serverPort != 0 {
			appConfig.App.Port = serverPort
		}
	}

	app := infra.New(appConfig)
	app.Start()
	// 之前是因为没有阻塞的starter，有了Iris就不用下面的了
	//c := make(chan int)
	//<- c
}

func ErrHandler(err error) {
	if err != nil {
		log.Fatal(err.Error())
		os.Exit(-1)
	}
}

func usage() {
	fmt.Fprintf(os.Stderr, `distill-infra version: brun/0.0.1
Usage: distill-infra [-h]

Options:
`)
	flag.PrintDefaults()
	os.Exit(0)
}

func defaultVersion() {
	fmt.Fprintf(os.Stderr, "version is:" + Version)
	os.Exit(0)
}